/**
 * 长按Hook
 * Story 5: Task 3 - 长按菜单功能
 */

import { useCallback, useRef } from 'react'
import { useHapticFeedback } from './useHapticFeedback'
import { useGestureConflictHandler } from './useGestureConflictHandler'

export interface LongPressOptions {
  threshold?: number
  onLongPress: (e: React.TouchEvent | React.MouseEvent) => void
  onLongPressStart?: () => void
  onLongPressEnd?: () => void
  enabled?: boolean
}

/**
 * 长按Hook
 * 提供长按检测功能，支持触觉反馈和视觉反馈
 */
export const useLongPress = ({
  threshold = 600,
  onLongPress,
  onLongPressStart,
  onLongPressEnd,
  enabled = true,
}: LongPressOptions) => {
  const timerRef = useRef<NodeJS.Timeout>()
  const isLongPressRef = useRef(false)
  const moveThreshold = 10 // 移动超过10px则取消长按
  const startPosRef = useRef<{ x: number; y: number } | null>(null)

  const { trigger: triggerHaptic } = useHapticFeedback()
  const { startGesture, endGesture, canStartGesture } = useGestureConflictHandler()

  const start = useCallback(
    (e: React.TouchEvent | React.MouseEvent) => {
      if (!enabled) return

      // 检查是否可以开始长按手势
      if (!canStartGesture('longPress')) {
        return
      }

      isLongPressRef.current = false

      // 记录起始位置
      const clientX =
        'touches' in e ? e.touches[0].clientX : (e as React.MouseEvent).clientX
      const clientY =
        'touches' in e ? e.touches[0].clientY : (e as React.MouseEvent).clientY
      startPosRef.current = { x: clientX, y: clientY }

      onLongPressStart?.()
      startGesture('longPress')

      timerRef.current = setTimeout(() => {
        isLongPressRef.current = true

        // 触觉反馈（三段震动）
        triggerHaptic('success')

        onLongPress(e)
      }, threshold)
    },
    [
      threshold,
      onLongPress,
      onLongPressStart,
      enabled,
      triggerHaptic,
      startGesture,
      canStartGesture,
    ]
  )

  const cancel = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }

    if (isLongPressRef.current) {
      onLongPressEnd?.()
    }

    endGesture('longPress')
    startPosRef.current = null
  }, [onLongPressEnd, endGesture])

  const move = useCallback(
    (e: React.TouchEvent | React.MouseEvent) => {
      if (!startPosRef.current) return

      const clientX =
        'touches' in e ? e.touches[0].clientX : (e as React.MouseEvent).clientX
      const clientY =
        'touches' in e ? e.touches[0].clientY : (e as React.MouseEvent).clientY

      const deltaX = Math.abs(clientX - startPosRef.current.x)
      const deltaY = Math.abs(clientY - startPosRef.current.y)

      // 如果移动距离超过阈值，取消长按
      if (deltaX > moveThreshold || deltaY > moveThreshold) {
        cancel()
      }
    },
    [cancel, moveThreshold]
  )

  const handlers = {
    onTouchStart: start,
    onTouchEnd: cancel,
    onTouchMove: move,
    onMouseDown: start,
    onMouseUp: cancel,
    onMouseMove: move,
    onMouseLeave: cancel,
    onContextMenu: (e: React.MouseEvent) => {
      // 阻止默认的右键菜单
      if (isLongPressRef.current) {
        e.preventDefault()
      }
    },
  }

  return {
    handlers,
    isLongPress: () => isLongPressRef.current,
  }
}
